package com.yuehuanghun.admin.generator.model;

import java.util.Date;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.util.ClassUtils;

import com.yuehuanghun.admin.generator.config.GenConfig;
import com.yuehuanghun.admin.generator.model.generator.AbstractTableGenerator;
import com.yuehuanghun.admin.generator.model.generator.TableGenerator;
import com.yuehuanghun.admin.generator.model.generator.TableGeneratorManager;
import com.yuehuanghun.framework.util.DatabaseUtil;
import com.yuehuanghun.framework.util.DatabaseUtil.DataBase;
import com.yuehuanghun.framework.util.StringUtils;

/**
 * 
 * 根据数据库表的元数据(metadata)创建Table对象
 * 
 * <pre>
 * getTable(sqlName) : 根据数据库表名,得到table对象
 * getAllTable() : 搜索数据库的所有表,并得到table对象列表
 * </pre>
 */
public class TableFactory {
	private final TableGenerator tableGenterator;

	private TableFactory(DataSource dataSource) {
		DataBase dataBase = DatabaseUtil.getDataBase(dataSource);
		tableGenterator = TableGeneratorManager.getTableGenerator(dataBase.getDbName());
		tableGenterator.setDataSource(dataSource);
		
		if(tableGenterator instanceof AbstractTableGenerator && StringUtils.isNotBlank(GenConfig.getDbCatalog())) {
			((AbstractTableGenerator)tableGenterator).setCatalog(GenConfig.getDbCatalog());
		}
		
		if(tableGenterator instanceof AbstractTableGenerator && StringUtils.isNotBlank(GenConfig.getDbSchema())) {
			((AbstractTableGenerator)tableGenterator).setSchema(GenConfig.getDbSchema());
		}
	}

	public static TableFactory newInstance(DataSource dataSource) {
		return new TableFactory(dataSource);
	}
	
	static {
	    if(ClassUtils.isPresent("oracle.jdbc.driver.OracleDriver", TableFactory.class.getClassLoader())) {
	        System.setProperty("oracle.jdbc.remarks", "true"); //ORACLE读取COLUMNS时获取备注信息
	    }
	}
	
	public Table getTable(String tableName) {
		return tableGenterator.genTable(tableName);
	}
	
	public List<Table> getSimpleTableInfo(String tableName, String tableComment, Date createTimeBegin, Date createTimeEnd, int pageNum, int pageSize) {
		return tableGenterator.getSimpleTableInfo(tableName, tableComment, createTimeBegin, createTimeEnd, pageNum, pageSize);
	}

}
